package com.sskj.bibi.ui.fragment;


import android.annotation.SuppressLint;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.header.MaterialHeader;
import com.sskj.bibi.R;
import com.sskj.bibi.R2;
import com.sskj.bibi.presenter.SlideHangqingFragmentPresenter;
import com.sskj.common.adapter.ItemClickSupport;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.DisposUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.rxbus.BibiCoinType;
import com.sskj.lib.mvchelper.RefreshDataSource;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RConfig.BIBI_FRAGMENT_SLIDE)//侧滑
public class SlideHangqingFragment extends BaseFragment<SlideHangqingFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;

    @Autowired
    String qu;
    private MVCCoolHelper<List<CoinBean>> mvcHelper;
    private SlimAdapter<CoinBean> slimAdapter;
    private Map<String, Disposable> timeMap = new HashMap<>();

    @Override
    protected int getLayoutId() {
        return R.layout.bibi_fragment_slide_hangqing;
    }

    @Override
    public SlideHangqingFragmentPresenter getPresenter() {
        return new SlideHangqingFragmentPresenter();
    }


    @SuppressLint("CheckResult")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWebSocketMessage(CoinBean stockSocketBean) {
        Flowable.fromIterable(slimAdapter.getData())
                .filter(item -> item.getCode().equals(stockSocketBean.getCode()))
                .subscribe(item -> {
                    if (Double.valueOf(stockSocketBean.getChange()) >= 0) {
                        stockSocketBean.setGreen(true);
                    } else {
                        stockSocketBean.setGreen(false);
                    }
                    stockSocketBean.setLight(true);
                    slimAdapter.getData().set(slimAdapter.getData().indexOf(item), stockSocketBean);
                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(stockSocketBean), 1);
                    DisposUtil.close(timeMap.get(item.getCode()));
                    Disposable subscribe = Flowable.timer(600, TimeUnit.MILLISECONDS)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(i -> {
                                stockSocketBean.setLight(false);
                                slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(stockSocketBean), 1);
                            });
                    timeMap.put(stockSocketBean.getCode(), subscribe);
                });
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        RxBus.getDefault().register(this);
        coolRefreshView.setPullHeader(new MaterialHeader(getActivity()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        initAdapter();
    }


    private void initAdapter() {
        slimAdapter = SlimAdapter.create().register(R.layout.bibi_recy_item_slide, new SlimInjector<CoinBean>() {
            @Override
            public void onInject(CoinBean stock, IViewInjector injector, List<Object> payloads) {
                injector
                        .text(R.id.tvType, stock.getCode().toUpperCase().replace("_", "/").split("/")[0])
                        .text(R.id.tvPrice, stock.getPrice())
                        .text(R.id.tvTypeRight, "/" + stock.getCode().toUpperCase().replace("_", "/").split("/")[1])
                        .textColor(R.id.tvPrice, ContextCompat.getColor(App.INSTANCE, stock.isUp() ? R.color.bibi_03c : R.color.bibi_e76));
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    RxBus.getDefault().post(new BibiCoinType(slimAdapter.getData().get(position).getCode(), qu));
                    getActivity().finish();
                });
        RefreshDataSource<CoinBean> refreshDataSource = new RefreshDataSource<CoinBean>() {
            @Override
            public Flowable<List<CoinBean>> loadData() {
                return mPresenter.getProduct(qu, null);
            }
        };
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        mvcHelper.setDataSource(refreshDataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();
    }

    @Override
    public void onDestroy() {
        RxBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
